<template>
  <Title>论文文本提取搜索</Title>
  <ShowBox>
    <!-- 上传 PDF 文件 -->
    <el-upload
      v-model:file-list="fileList"
      class="upload-demo"
      auto-load=False
      action="http://localhost:8080/upload"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      multiple
    >
      <el-button type="primary">上传 PDF 文件</el-button>
      <template #tip>
        <div class="el-upload__tip">
          支持 PDF 文件上传，上传后系统将提取图片和文本。
        </div>
      </template>
    </el-upload>

    <!-- 提取结果 -->
    <div v-if="extractedData" class="result">
      <p>提取结果存储路径：</p>
      <ul>
        <li>图片存储路径: {{ extractedData.imagePath }}</li>
        <li>文本存储路径: {{ extractedData.textPath }}</li>
      </ul>
      <p>提取的图片：</p>
      <div class="image-gallery">
        <img
          v-for="(image, index) in extractedData.images"
          :key="index"
          :src="image"
          alt="提取的图片"
          class="extracted-image"
        />
      </div>
    </div>
  </ShowBox>
</template>

<script setup>
import ShowBox from '@/components/ShowBox.vue'
import Title from '@/components/Title.vue'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

// 上传文件列表
const fileList = ref([])

// 提取结果数据
const extractedData = ref(null)

// 文件类型检查
const beforeUpload = (file) => {
  const isPDF = file.type === 'application/pdf'
  if (!isPDF) {
    ElMessage.error('只能上传 PDF 文件！')
  }
  return isPDF
}

// 成功处理
const handleSuccess = (response) => {
  if (response && response.success) {
    extractedData.value = {
      imagePath: response.imagePath,
      textPath: response.textPath,
      images: response.images,
    }
    ElMessage.success('PDF 提取成功！')
  } else {
    ElMessage.error('后端提取失败，请检查后端逻辑！')
  }
}

// 错误处理
const handleError = () => {
  ElMessage.error('文件上传失败，请检查网络或后端接口！')
}
</script>

<style scoped>
.result {
  margin-top: 20px;
}
.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}
.extracted-image {
  width: 150px;
  height: auto;
  border: 1px solid #ccc;
  border-radius: 5px;
}
</style>
